package top.toptimus.util;

import com.thoughtworks.xstream.XStream;

import javax.validation.constraints.NotNull;

public class XmlUtil {
    public static XStream xStreamTo = new XStream();
    public static XStream xStreamFrom = new XStream();

    static {
        xStreamTo.autodetectAnnotations(true);
    }

    public static String toXml(@NotNull Object bean) {
        try {
            String top = "<?xml version='1.0' encoding='UTF-8'?>\n";

            return top + xStreamTo.toXML(bean);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static <T> T fromXml(@NotNull String xml, @NotNull Class<T> clzz) {
        try {
            xStreamFrom.processAnnotations(clzz);
            xStreamFrom.setClassLoader(clzz.getClassLoader());
            xStreamFrom.allowTypes(new Class[]{clzz});

            return (T) xStreamFrom.fromXML(xml);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }


}
